<template>
     <div class="main">
      <div  class="el-upload-list--picture-card">
        <div class="el-upload--picture-card" @click="editCropper">
          <img v-if="picture" :src="picture" style="width:147px;height:147px;border-radius:6px"/>
          <el-icon v-else class="el-icon-plus"></el-icon>
        </div>
      </div>
      
      <el-dialog
         :visible="open"
          title="裁剪图片"
          class="dialog"
          append-to-body
          @close="open=false"
          :close-on-click-modal="false"
          :width="dialogWidth"
        >
          <div class="cjBox">
            <vueCropper ref="cropper" 
              @realTime="realTime" 
              :img="option.img" 
              :autoCrop="option.autoCrop"
              :autoCropWidth="option.autoCropWidth"
              :autoCropHeight="option.autoCropHeight" 
              :fixedBox="option.fixedBox" 
              :fixedNumber="option.fixedNumber"
              :outputType="option.outputType" />
          </div>
          <div class="mt10">
            <el-upload class="mb10" action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
              <el-button size="small"> 选择图片</el-button>
            </el-upload>
            <el-button style="margin-left:10px" icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
            <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
            <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
            <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
            <el-button style="margin-left:10px" type="success" icon="el-icon-crop" size="small" @click="finish">确定</el-button>
          </div>
      </el-dialog>
    </div>
</template>

<script>
import { VueCropper } from 'vue-cropper';
export default {
  components: { VueCropper },
  name: "Aside",
  props: ['transfer'],
  data() {
    return {
      open:false,
      previews: {},
        previewStyle: {},
        option: {
          img: '', // 裁剪图片的地址
          autoCrop: true, // 是否默认生成截图框  (默认:false)
       //   outputSize: 1, // 裁剪生成图片的质量  (默认:1)
       //   full: false, // 是否输出原图比例的截图 选true生成的图片会非常大  (默认:false)
         // canMove: true, // 上传图片是否可以移动  (默认:true)
          // canMoveBox: false, // 截图框能否拖动  (默认:true)
          canScale: true,
        //  centerBox: true,//截图框是否被限制在图片里面  (默认:false)
          autoCropWidth: 300, // 默认生成截图框宽度  (默认:80%)
          autoCropHeight: 400, // 默认生成截图框高度  (默认:80%)
          fixedBox: true, // 固定截图框大小 不允许改变  (默认:false)
       //   fixed: true,//是否开启截图框宽高固定比例  (默认:false)
           fixedNumber: [3, 4],//截图框宽高比例  [宽,高](默认[1:1])
          outputType: 'png', // 裁剪生成图片的格式 可选值 jpeg, png, webp
        },
        picture:'',
        dialogWidth:'750px'
    }
  },
  mounted() {
    console.log(this)
      if(window.screen.width<768){
         this.dialogWidth="100%"
      }else{
        this.dialogWidth="750px"
      }
  },
  methods: {
    editCropper(){
      this.open=true
    },
        // 覆盖默认的上传行为
      requestUpload() {
      },
      // 上传预处理
      beforeUpload(file) {
        if (file.type.indexOf("image/") == -1) {
          this.$message.error("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
        } else {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            this.option.img = reader.result;
          };
        }
      },
      realTime(data) {  //实时预览
        this.previewStyle = {
          width: data.w + "px",
          height: data.h + "px",
          overflow: "hidden",
          margin: "0",
          borderRadius: "50%",
        }
        this.previews = data
      },
      finish() {  // 下载/上传 预览图
        let fileName = '裁剪图.png'
        this.$refs.cropper.getCropBlob((data) => { //获取截图的 blob 数据
          // 上传图片
         //  this.uploadImg(data, fileName)

          this.transfer(data)
          let url = window.URL.createObjectURL(data)
          this.picture=url
          this.open=false
         //传回父组件
         
        
         // this.downloadIamge1(url, fileName)  //本地下载方法1
          // this.downloadIamge2(url, fileName)  //本地下载方法2
        });
      
      },
      // 上传图片
      uploadImg(data, fileName) {
        let formData = new FormData();
        formData.append('file', data, fileName);
        // 上传到服务器
        this.request.post("/file/upload", formData).then(res => {
                if(res!=''){
                    this.picture=res
                   this.open=false
                  return this.transfer(res)
                }
                            // if (res.code === 200) {
                            //    console.log(res)
                            // } else {
                            //     this.$message.error(res.message)
                            // }
                        })
      },
      downloadIamge1(url, fileName) {  // 下载图片
        let link = document.createElement('a')
        link.style.display = 'none'
        link.setAttribute('href', url)
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link) //下载完成移除元素
        window.URL.revokeObjectURL(url) //释放掉blob对象
      },
      downloadIamge2(imgsrc, fileName) {//下载图片
        let image = new Image();
        // 解决跨域 Canvas 污染问题
        image.setAttribute("crossOrigin", "anonymous");
        image.onload = function () {
          let canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          let context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);
          let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
          let a = document.createElement("a"); // 生成一个a元素
          let event = new MouseEvent("click"); // 创建一个单击事件
          a.href = url; // 将生成的URL设置为a.href属性
          a.download = fileName; // 设置图片名称
          a.dispatchEvent(event); // 触发a的单击事件
          window.URL.revokeObjectURL(imgsrc) //释放掉blob对象
        };
        image.src = imgsrc;
      },
      // 向左旋转
      rotateLeft() {
        this.$refs.cropper.rotateLeft();
      },
      // 向右旋转
      rotateRight() {
        this.$refs.cropper.rotateRight();
      },
      // 图片缩放
      changeScale(num) {
        num = num || 1;
        this.$refs.cropper.changeScale(num);
      },
    },
}
</script>

<style scoped>
  .main {
    position: relative;
  }
  .mt10{
    display: flex;
    margin-top:10px;
  }
  .el-upload--picture-card{
    display: flex;
    justify-content: center;
    align-items: center;
  }
  /* .dialog{
    width:750px;
    height:auto
  } */
  .cjBox{
    width:700px;
    height: 600px;
    overflow: hidden;
  }
  @media (max-width: 768px){
    /* .el-dialog {
        margin-top: 20px!important;
    } */
    /* .dialog{
    width:100%;
    height:auto
  } */
  /* :deep(.el-dialog) {
    margin:0!important;
    width:100%!important;

  } */
  .cjBox{
    width:100%;
    height: 420px
  }
}
</style>
